package com.zhouyibike.uu.ui.activity.yihoudong;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.LimitLine;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.formatter.ValueFormatter;
import com.github.mikephil.charting.interfaces.datasets.IBarDataSet;
import com.github.mikephil.charting.utils.ViewPortHandler;
import com.google.gson.Gson;
import com.zhouyibike.uu.R;
import com.zhouyibike.uu.config.Config;
import com.zhouyibike.uu.entity.YiHuoDongResult;
import com.zhouyibike.uu.entity.YiQuanForTranferAmountResult;
import com.zhouyibike.uu.entity.YiQuanListResult;
import com.zhouyibike.uu.http.ApiCallback;
import com.zhouyibike.uu.ui.activity.mywallet.SaomafukuanActivity;
import com.zhouyibike.uu.ui.activity.mywallet.ShoukuanActivity;
import com.zhouyibike.uu.ui.base.BaseActivity;
import com.zhouyibike.uu.utils.PermissionTool;
import com.zhouyibike.uu.utils.Util;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import observablescrollview.ObservableScrollView;
import observablescrollview.ObservableScrollViewCallbacks;
import observablescrollview.ScrollState;

/**
 * Created by Zy on 2017/10/11.
 */
public class YihuodongmainFragment extends Fragment implements ObservableScrollViewCallbacks, View.OnClickListener {
    private BarChart mLineChart;
    private ObservableScrollView mScrollView;
    public int scy = 0;//移动距离
    private TextView tvbuying, tvbuy, tvsell, tvname, yihuodong_mynum, tvtransing;
    public int cansellyiquan = 0;
    private ImageView rengouyiquaniv, zhuanrangyiquaniv, yiquanmingxiiv;
    private LinearLayout yiquansaoyisaoiv, yiquanshoukuaniv;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        Bundle b = getArguments();
        View view = View.inflate(getActivity(), R.layout.fragment_yihuodongmain, null);
        initView(view);
        initlistener();
        dataf();
        return view;
    }

    private void initlistener() {
        rengouyiquaniv.setOnClickListener(this);
        zhuanrangyiquaniv.setOnClickListener(this);
        yiquanmingxiiv.setOnClickListener(this);
        yiquanshoukuaniv.setOnClickListener(this);
        yiquansaoyisaoiv.setOnClickListener(this);
    }

    private void initView(View view) {
        yiquansaoyisaoiv = view.findViewById(R.id.yiquansaoyisaoiv);
        yiquanshoukuaniv = view.findViewById(R.id.yiquanshoukuaniv);
        rengouyiquaniv = view.findViewById(R.id.rengouyiquaniv);
        zhuanrangyiquaniv = view.findViewById(R.id.zhuanrangyiquaniv);
        yiquanmingxiiv = view.findViewById(R.id.yiquanmingxiiv);
        tvbuy = view.findViewById(R.id.keshiyongyiquannum);
        tvbuying = view.findViewById(R.id.qianggouzhongyiquannum);
        tvsell = view.findViewById(R.id.kezhuanrangyiquannum);
//        tvname=view.findViewById(R.id.keshiyongyiquannum);
        yihuodong_mynum = view.findViewById(R.id.myhaveyiquannum);
        tvtransing = view.findViewById(R.id.zhuanrangzhongyiquannum);
        mLineChart = (BarChart) view.findViewById(R.id.lineChart);
        initChart();
        mScrollView = (ObservableScrollView) view.findViewById(R.id.scroll);
        mScrollView.setScrollViewCallbacks(this);
//        setData(7, 5);
    }


    //设置chart基本属性
    private void initChart() {
        //描述信息
//        Description description = new Description();
//        description.setText("我是描述信息");
        //设置描述信息
//        mLineChart.setDescription(description);
        //设置没有数据时显示的文本
        mLineChart.setDescription("");
        mLineChart.setNoDataTextDescription("");
        mLineChart.setNoDataText("");
        //设置是否绘制chart边框的线
        mLineChart.setDrawBorders(false);
        //设置chart边框线颜色
        mLineChart.setBorderColor(Color.WHITE);
        //设置chart边框线宽度
        mLineChart.setBorderWidth(1f);
        //设置chart是否可以触摸
        mLineChart.setTouchEnabled(false);
        //设置是否可以拖拽
        mLineChart.setDragEnabled(false);
        //设置是否可以缩放 x和y，默认true
        mLineChart.setScaleEnabled(false);
        //设置是否可以通过双击屏幕放大图表。默认是true
        mLineChart.setDoubleTapToZoomEnabled(false);
        //设置chart动画
        mLineChart.animateXY(1000, 0);

        //=========================设置图例=========================
        // 像"□ xxx"就是图例
        Legend legend = mLineChart.getLegend();
        //设置图例显示在chart那个位置 setPosition建议放弃使用了
        //设置垂直方向上还是下或中
        legend.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
        //设置水平方向是左边还是右边或中
        legend.setHorizontalAlignment(Legend.LegendHorizontalAlignment.RIGHT);
        //设置所有图例位置排序方向
        legend.setOrientation(Legend.LegendOrientation.HORIZONTAL);
        //设置图例的形状 有圆形、正方形、线
        legend.setForm(Legend.LegendForm.CIRCLE);
        //是否支持自动换行 目前只支持BelowChartLeft, BelowChartRight, BelowChartCenter
        legend.setWordWrapEnabled(true);
        legend.setEnabled(false);

        //=======================设置X轴显示效果==================
        XAxis xAxis = mLineChart.getXAxis();
        //是否启用X轴
        xAxis.setEnabled(true);
        //是否绘制X轴线
        xAxis.setDrawAxisLine(false);
        xAxis.setTextColor(getResources().getColor(R.color.text_main_3));
        //设置X轴上每个竖线是否显示
        xAxis.setDrawGridLines(false);
        xAxis.setTextSize(9f);
        //设置是否绘制X轴上的对应值(标签)
        xAxis.setDrawLabels(true);
        //设置X轴显示位置
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        //设置竖线为虚线样式
        // xAxis.enableGridDashedLine(10f, 10f, 0f);
        //设置x轴标签数
//        xAxis.setLabelCount(5, true);
        //图表第一个和最后一个label数据不超出左边和右边的Y轴
        // xAxis.setAvoidFirstLastClipping(true);

        //设置限制线 12代表某个该轴某个值，也就是要画到该轴某个值上
        LimitLine limitLine = new LimitLine(12);
        //设置限制线的宽
        limitLine.setLineWidth(1f);
        //设置限制线的颜色
        limitLine.setLineColor(Color.WHITE);
        //设置基线的位置
        limitLine.setLabelPosition(LimitLine.LimitLabelPosition.LEFT_TOP);
        limitLine.setLabel("马丹我是基线，也可以叫我水位线");
        //设置限制线为虚线
//        limitLine.enableDashedLine(10f, 10f, 0f);
        //左边Y轴添加限制线
//        axisLeft.addLimitLine(limitLine);

        //=================设置左边Y轴===============
        YAxis axisLeft = mLineChart.getAxisLeft();
        //是否启用左边Y轴
        axisLeft.setEnabled(false);
        axisLeft.setTextColor(Color.WHITE);
        axisLeft.setGridColor(Color.WHITE);
        axisLeft.setAxisLineColor(Color.WHITE);
        //设置最小值（这里就按demo里固死的写）
//        axisLeft.setAxisMinValue(1);
//        //设置最大值（这里就按demo里固死的写了）
//        axisLeft.setAxisMaxValue(20);
        //设置横向的线为虚线
//        axisLeft.enableGridDashedLine(10f, 10f, 0f);
        //axisLeft.setDrawLimitLinesBehindData(true);


        //====================设置右边的Y轴===============
        YAxis axisRight = mLineChart.getAxisRight();
        //是否启用右边Y轴
        axisRight.setEnabled(false);
        axisRight.setTextColor(Color.WHITE);
        axisRight.setGridColor(Color.WHITE);
        axisRight.setAxisLineColor(Color.WHITE);
        //设置最小值（这里按demo里的数据固死写了）
//        axisRight.setAxisMinValue(1);
//        //设置最大值（这里按demo里的数据固死写了）
//        axisRight.setAxisMaxValue(20);
        //设置横向的线为虚线
//        axisRight.enableGridDashedLine(10f, 10f, 0f);

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {

            case R.id.rengouyiquaniv:
                Intent intent = new Intent(getActivity(), YijuangounaiActivity.class);//跳转购买100
                startActivityForResult(intent, 188);
                break;
            case R.id.zhuanrangyiquaniv:
                Intent intent2 = new Intent(getActivity(), YihuodongzhuanrangActivity.class);//跳转转让200
                if (((YihuodongActivity3) getActivity()).f1 != null) {
                    intent2.putExtra("cansellnum", ((YihuodongActivity3) getActivity()).f1.cansellyiquan);
                } else {
                    intent2.putExtra("cansellnum", 0);
                }
                startActivityForResult(intent2, 188);
                break;
            case R.id.yiquanmingxiiv:
                startActivity(new Intent(getActivity(), MyYiquanmingxiActivity.class));
                break;
            case R.id.yiquansaoyisaoiv://123付款
                if (PermissionTool.isCameraCanUse()) {
                    startActivityForResult(new Intent(getActivity(), SaomafukuanActivity.class), 123);
                } else {
                    ((BaseActivity) getActivity()).toastShow("没有获取相机权限,请手动设置应用权限");
                }
                break;
            case R.id.yiquanshoukuaniv://321收款
                startActivityForResult(new Intent(getActivity(), ShoukuanActivity.class), 321);
                break;
            default:
                break;
        }
    }

    public class MyValueFormatter implements ValueFormatter {

        DecimalFormat df = new DecimalFormat("######0.00");
        DecimalFormat df2 = new DecimalFormat("######0");

        @Override
        public String getFormattedValue(float value, Entry entry, int dataSetIndex, ViewPortHandler viewPortHandler) {
//            return df.format(value) + "万";
//            return null;
            return df2.format(value);
        }
    }

    private void setData(int count, float range, YiQuanForTranferAmountResult model) {
        ArrayList<YiQuanListResult> list1 = new ArrayList<YiQuanListResult>();
        ArrayList<YiQuanListResult> list2 = new ArrayList<YiQuanListResult>();
        list1.clear();
        list2.clear();
        for (int i = 0; i < model.getData().getBuyYiQuanList().size(); i++) {
            list2.add(new Gson().fromJson(model.getData().getBuyYiQuanList().get(i), YiQuanListResult.class));
        }
        for (int i = 0; i < model.getData().getTransferYiQuanList().size(); i++) {
            list1.add(new Gson().fromJson(model.getData().getTransferYiQuanList().get(i), YiQuanListResult.class));
        }
        ArrayList<String> xVals = new ArrayList<String>();
        xVals.clear();
        for (int i = 0; i < list1.size(); i++) {
            String iii = "";
            try {
                iii = list1.get(i).getDate().split(" ")[0].substring(5);
            } catch (Exception e) {
                e.printStackTrace();
                iii = "";
            }
            xVals.add(iii);
        }

        ArrayList<BarEntry> yVals1 = new ArrayList<BarEntry>();
        yVals1.clear();
        for (int i = 0; i < list1.size(); i++) {
            float mult = range / 2f;
            float val = (float) list1.get(i).getMoney();// + (float)
            // ((mult *
            // 0.1) / 10);
            yVals1.add(new BarEntry(val, i));
        }

        ArrayList<BarEntry> yVals2 = new ArrayList<BarEntry>();
        yVals2.clear();
        for (int i = 0; i < list2.size(); i++) {
            float mult = range;
            float val = (float) list2.get(i).getMoney();// + (float)
            // ((mult *
            // 0.1) / 10);
            yVals2.add(new BarEntry(val, i));
        }
//
//        LineDataSet set1, set2;
//
////        if (mLineChart.getData() != null &&
////                mLineChart.getData().getDataSetCount() > 0) {
////            set1 = (LineDataSet) mLineChart.getData().getDataSetByIndex(0);
////            set2 = (LineDataSet) mLineChart.getData().getDataSetByIndex(1);
////            set1.setYVals(yVals1);
////            set2.setYVals(yVals2);
////            mLineChart.getData().setXVals(xVals);
////            mLineChart.notifyDataSetChanged();
////        } else
//        {
//            // create a dataset and give it a type
//            set1 = new LineDataSet(yVals1, "DataSet 1");
//
//            set1.setAxisDependency(YAxis.AxisDependency.LEFT);
//            // set1.setFillAlpha(110);
//            // set1.setFillColor(Color.RED);
//
//            // set the line to be drawn like this "- - - - - -"
////            set1.enableDashedLine(10f, 5f, 0f);
////            set1.enableDashedHighlightLine(10f, 5f, 0f);
//            set1.setColor(getResources().getColor(R.color.radio_button_selected_color));
//            set1.setCircleColor(getResources().getColor(R.color.radio_button_selected_color));
//            set1.setValueTextColor(getResources().getColor(R.color.radio_button_selected_color));
////            set1.setValueFormatter(new MyValueFormatter());
//            set1.setLineWidth(2f);
//            set1.setCircleRadius(5f);
//            set1.setCircleHoleRadius(3.5f);
//            set1.setDrawCircleHole(true);
//            set1.setValueTextSize(12f);
//            set1.setDrawFilled(false);
//            set1.setValueFormatter(new MyValueFormatter());
//            //set1.setFillFormatter(new MyFillFormatter(0f));
//            //set1.setDrawHorizontalHighlightIndicator(false);
//            //set1.setVisible(false);
//            //set1.setCircleHoleColor(Color.WHITE);
//
//            // create a dataset and give it a type
//            set2 = new LineDataSet(yVals2, "DataSet 2");
//            set2.setAxisDependency(YAxis.AxisDependency.LEFT);
//            set2.setColor(getResources().getColor(R.color.zhexiantutvvalue));
//            set2.setCircleColor(getResources().getColor(R.color.zhexiantutvvalue));
//            set2.setValueTextColor(getResources().getColor(R.color.zhexiantutvvalue));
//            set2.setValueFormatter(new MyValueFormatter());
//            set2.setLineWidth(2f);
//            set2.setCircleRadius(5f);
//            set2.setCircleHoleRadius(3.5f);
//            set2.setDrawCircleHole(true);
//            set2.setValueTextSize(12f);
//            set2.setDrawFilled(false);
////            set2.setValueFormatter(new MyValueFormatter());
//            //set2.setFillFormatter(new MyFillFormatter(900f));
//            set1.setYVals(yVals1);
//            set2.setYVals(yVals2);
//            ArrayList<ILineDataSet> dataSets = new ArrayList<ILineDataSet>();
//            dataSets.add(set2);
//            dataSets.add(set1); // add the datasets
//            // create a data object with the datasets
//            LineData data = new LineData(xVals, dataSets);
////            data.setValueTextColor(Color.WHITE);
//            data.setValueTextSize(9f);
//            // set data
//            mLineChart.notifyDataSetChanged();
//            mLineChart.setData(data);
//            mLineChart.notifyDataSetChanged();
//            mLineChart.invalidate();
//        }
        BarDataSet set1;
        set1 = new BarDataSet(yVals1, "DataSet");
//        set1.setBarSpacePercent(60f);
        set1.setColor(getResources().getColor(R.color.zhexiantutvvalue));
        set1.setValueTextColor(getResources().getColor(R.color.transparent));
        set1.setValueFormatter(new MyValueFormatter());
        BarDataSet set2;
        set2 = new BarDataSet(yVals2, "DataSet2");
        set2.setColor(getResources().getColor(R.color.radio_button_selected_color));
        set2.setValueTextColor(getResources().getColor(R.color.transparent));
        set2.setValueFormatter(new MyValueFormatter());
        ArrayList<IBarDataSet> dataSets = new ArrayList<IBarDataSet>();
        dataSets.add(set2);
        dataSets.add(set1);
        BarData data = new BarData(xVals, dataSets);
        data.setValueTextSize(10f);
        mLineChart.notifyDataSetChanged();
        mLineChart.setData(data);
        mLineChart.notifyDataSetChanged();
        mLineChart.invalidate();
    }

    @Override
    public void onScrollChanged(int scrollY, boolean firstScroll, boolean dragging) {
        int baseColor = getResources().getColor(R.color.radio_button_selected_color);
//        float alpha = Math.min(1, (float) scrollY / (mParallaxImageHeight-150));
        Log.e("onScrollChanged: ", scrollY + "");
        scy = scrollY;
        if (scrollY >= Util.dp2px(getActivity(), 26)) {
            ((YihuodongActivity3) getActivity()).bglybglybgly.setBackgroundColor(baseColor);
        } else {
            ((YihuodongActivity3) getActivity()).bglybglybgly.setBackgroundColor(getResources().getColor(R.color.transparent));
        }
        if (((YihuodongActivity3) getActivity()).curpage == 1) {
            ((YihuodongActivity3) getActivity()).settitleyanse(0);
        }
//        ViewHelper.setTranslationY(mImageView, scrollY / 2);
    }

    @Override
    public void onDownMotionEvent() {

    }

    @Override
    public void onUpOrCancelMotionEvent(ScrollState scrollState) {

    }

    public void dataf() {
        getYihuodonginfo();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode==321)
        {
            dataf();
        }
    }

    private void getyiquanlistMsg() {//查看翼券交易信息表7天
        Map<String, String> params = new HashMap<>();
        params.put("token", ((BaseActivity) getActivity()).preferences.getString("token", ""));
        ((BaseActivity) getActivity()).addSubscription(((BaseActivity) getActivity()).apiStores.YiQuanForTranferAmount(params),
                new ApiCallback<YiQuanForTranferAmountResult>() {

                    @Override
                    public void onSuccess(YiQuanForTranferAmountResult model) {
                        if (model.getStatus() == Config.SUCCESSCODE) {
                            setData(7, 5, model);
                        } else {
                            ((BaseActivity) getActivity()).toastShow(model.getMessage());
                        }
                    }

                    @Override
                    public void onFailure(String msg) {
                        ((BaseActivity) getActivity()).toastShow(msg);

                    }

                    @Override
                    public void onFinish() {
                        ((BaseActivity) getActivity()).dismissProgressDialog();
                    }
                });
    }

    /**
     * 获取用户自己的翼券数量，翼券市场
     */
    private void getYihuodonginfo() {
        Map<String, String> params = new HashMap<>();
        params.put("token", ((BaseActivity) getActivity()).preferences.getString("token", ""));
        ((BaseActivity) getActivity()).showProgressDialog();
        ((BaseActivity) getActivity()).addSubscription(((BaseActivity) getActivity()).apiStores.YiHuoDong(params),
                new ApiCallback<YiHuoDongResult>() {
                    @Override
                    public void onSuccess(YiHuoDongResult model) {
                        if (model.getStatus() == Config.SUCCESSCODE) {
                            initData2(model);
                        } else {
                            ((BaseActivity) getActivity()).toastShow(model.getMessage());
                        }
                    }

                    @Override
                    public void onFailure(String msg) {
                        yihuodong_mynum.setText("" + 0);
                        tvsell.setText("" + 0);
                        tvbuy.setText("" + 0);
                        tvbuying.setText("" + 0);
                        tvtransing.setText("0");
//                        tvname.setText(((BaseActivity)getActivity()).preferences.getString("mobile", ""));
                        ((BaseActivity) getActivity()).toastShow(msg);
                    }

                    @Override
                    public void onFinish() {
//                        dismissProgressDialog();
                        getyiquanlistMsg();
                    }
                });
    }

    private void initData2(YiHuoDongResult model) {
        cansellyiquan = model.getData().getTransferAmount();
//        yihuodong_mynum.setText("我的翼券 " + model.getData().getUsegeAmount());
//        tvsell.setText("可转让 " + model.getData().getTransferAmount());
//        tvbuy.setText("可使用 " + model.getData().getAmount());
        yihuodong_mynum.setText("" + model.getData().getAmount());
        tvsell.setText("" + model.getData().getTransferAmount());
        tvbuy.setText("" + model.getData().getUsegeAmount());
        tvbuying.setText("" + model.getData().getbuyingAmount());
        tvtransing.setText("" + model.getData().gettransferingAmount());
//        tvname.setText( ((BaseActivity)getActivity()).preferences.getString("mobile", ""));
//        if (!TextUtils.isNullorEmpty(model.getData().getHeadImg())) {
////            http://img.ivsky.com/img/tupian/pre/201104/16/anhui_huangshan_fengjing-055.jpg
//            Picasso.with(this).load(model.getData().getHeadImg()) .transform(ImgUtils.Picassocompress(mCircleImageView)).error(R.mipmap.head_moren).placeholder(R.mipmap.head_moren).networkPolicy(NetworkPolicy.NO_CACHE,NetworkPolicy.NO_STORE).into(mCircleImageView);
//        }
        //   Picasso.with(this).load("http://img.ivsky.com/img/tupian/pre/201104/16/anhui_huangshan_fengjing-055.jpg").into(mCircleImageView);
    }
}
